package some

import (
	"bytes"
	"fmt"

	"gitee.com/thubcc/p2pgit/format"
	"gitee.com/thubcc/p2pgit/types"
)

// NewPackCBForHTTPPost pack call back
func NewPackCBForHTTPPost(gs types.SomeGeter) func(*format.Header, []byte) error {
	pps := types.NewRawer(Geter2Rawer(gs))
	return func(h *format.Header, b []byte) (cerr error) {
		pf := new(bytes.Buffer)
		pf.Reset()
		buf := h.ToByte()

		if h.Header32.Size != uint32(len(b)+len(buf)) {
			return fmt.Errorf("Size error:%d,%d,%d", len(b), len(buf), h.Header32.Size)
		}
		h.Header32.HCRC32 = h.Header32.CRC()
		h32 := h.Header32.ToHash256()
		_, cerr = pf.Write(h32[:])
		if cerr != nil {
			return
		}

		_, cerr = pf.Write(buf)
		if cerr != nil {
			return
		}
		_, cerr = pf.Write(b)
		pfb := pf.Bytes()
		cerr = pps.Put(pfb)
		// for _, p := range pps {
		// 	cerr = p.Put(pfb)
		// 	if cerr != nil && cerr != constant.ErrorNoMatch {
		// 		return
		// 	}
		// }
		return
	}
}
